import React, { CSSProperties, useCallback, useContext, useEffect, useMemo, useState } from 'react';
import { AudioType } from '../../defined';
import { FPlayerContext } from '../../index';
import Table from '../../common/table';
import './index.scss';
interface PlayListProps {
  isShow: boolean;
  playList: Array<AudioType>;
  historyAudioList: Array<AudioType>;
  themeColor?: string;
  _ref: any;
  toggleAudio: (isAutoToggle: boolean, newCurrentAudioIndex: number) => void; // 切换音乐
}
enum playListType {
  PLAT_LIST,
  HISTORY_LIST
}
const FplayerPlayList: React.FC<PlayListProps> = (props: PlayListProps) => {
  const { isShow = false, playList = [], historyAudioList = [], themeColor = '', _ref = null, toggleAudio } = props;
  const currentAudio = useContext(FPlayerContext);
  const [_type, setType] = useState<playListType>(0);

  const activeStyle = useMemo(
    (): CSSProperties => ({
      background: themeColor,
      color: '#fff',
      transition: 'all .2s'
    }),
    [themeColor]
  );
  const playListClass = useMemo(() => ['fplayer_playlist', isShow ? 'ani_enter' : 'ani_leave'].join(' '), [isShow]);

  const innerToggleAudio = useCallback(record => {
    const { id } = record;
    const index = playList.findIndex(item => item.id === id);
    toggleAudio(false, index);
  }, []);

  const column = [
    {
      title: '',
      dataIndex: '',
      width: 50,
      className: 'table_index',
      render: (text: string, record: any, index: number) =>
        (currentAudio?.id === record.id ? (
          <span className="iconfont fplayer-volume" style={{ color: themeColor }} />
        ) : (
          <span>{index + 1}</span>
        ))
    },
    {
      title: '歌曲名称',
      dataIndex: 'name',
      width: 150,
      className: 'table_name',
      render: (text: string, record: any, index: number) => (
        <span
          style={{ color: currentAudio?.id === record.id ? themeColor : '' }}
          onClick={(): void => innerToggleAudio(record)}>
          {text}
        </span>
      )
    },
    {
      title: '歌曲作者',
      dataIndex: 'artist'
    },
    {
      title: '时长',
      dataIndex: 'time'
    }
  ];
  return (
    <div className={playListClass} ref={_ref}>
      <div className="head">
        <div className="btn_warp">
          <div style={_type === playListType.PLAT_LIST ? activeStyle : {}} onClick={() => setType(0)}>
            播放列表
          </div>
          <div style={_type === playListType.HISTORY_LIST ? activeStyle : {}} onClick={() => setType(1)}>
            历史记录
          </div>
        </div>
      </div>
      <div className="main">
        {_type === playListType.PLAT_LIST ? (
          <Table className="table" dataSource={playList} column={column} width={386} />
        ) : (
          <Table className="table" dataSource={historyAudioList} column={column} width={386} />
        )}
      </div>
    </div>
  );
};

export default FplayerPlayList;
